package com.snap.vseries.adapter;

import android.content.Context;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import com.snap.vseries.R;
import com.snap.vseries.base.BaseRecycleAdapter;
import com.snap.vseries.base.BaseViewHolder;
import com.snap.vseries.bean.ExpEntity;
import com.snap.vseries.manager.FileManager;
import com.snap.vseries.model.DBManager;
import com.snap.vseries.utils.ToastUtils;

import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.util.List;

public class TemplateAdapter extends BaseRecycleAdapter<ExpEntity> {

    private ItemTouchHelper mItemHelper;

    public TemplateAdapter(Context context, List<ExpEntity> dataList, ItemTouchHelper helper) {
        super(context, dataList);
        this.mItemHelper = helper;
    }

    @Override
    public void bindData(BaseViewHolder holder, ExpEntity data, int position) {
        holder.setText(R.id.template_name_tv, data.getTestProject());
        holder.getView(R.id.delete_template_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delete(data);
            }
        });
        holder.getView(R.id.sort_template_iv).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mItemHelper != null) {
                    mItemHelper.startDrag(holder);
                }
                return false;
            }
        });
    }

    private void delete(ExpEntity data) {
        DBManager.get().deleteTemplate(new UpdateOrDeleteCallback() {
            @Override
            public void onFinish(int rowsAffected) {
                notifyDataSetChanged();
                if (rowsAffected > 0) {
                    FileManager.getInstance().removeTempData(data.getTestProject());
                    ToastUtils.get().showText("删除项目成功");
                }
            }
        }, data.getTestProject());
    }

    @Override
    public int getLayoutId(int viewType) {
        return R.layout.item_template;
    }
}
